/**
 * 文件名：CdnContextLoaderListener.java
 * 
 * 版本信息：
 * 日期：2013-12-3
 * Copyright 足下 Corporation 2013
 * 版权所有
 * 
 */
package com.hugedata.cdn.startup;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * 
 * 项目名称：cdn 类名称：CdnContextLoaderListener 类描述： 创建人：zhaoaihua 创建时间：2013-12-3
 * 下午3:44:06 修改备注：
 * 
 * @version
 * 
 */
public class CdnContextLoaderListener extends ContextLoaderListener
{
    private static final String SYSTEM_INIT_STARTUP_BEAN = "systemInitStartupBean";

    private SystemInitLoader initLoader;

    protected final Log log = LogFactory.getLog(getClass());
    private static Logger ossLogger = Logger
            .getLogger(CdnContextLoaderListener.class);

    /**
     * {@inheritDoc}
     */
    public void contextInitialized(ServletContextEvent event)
    {
        long begin = System.currentTimeMillis();

        log.debug("System Init Loader  Starting...");

        try
        {
            super.contextInitialized(event);

            ServletContext servletContext = event.getServletContext();
            ApplicationContext applicationContext = WebApplicationContextUtils
                    .getWebApplicationContext(servletContext);

            initLoader = (SystemInitLoader) applicationContext
                    .getBean(SYSTEM_INIT_STARTUP_BEAN);

            initLoader.init();
            
        }
        catch (RuntimeException e)
        {
            processFailure(e);
            throw e;
        }
        catch (InterruptedException e)
        {
            processFailure(e);
            throw new IllegalStateException(e);
        }
        catch (Error e)
        {
            processFailure(e);
            throw e;
        }

        long end = System.currentTimeMillis();

        log.debug("System Init Loader  Start success in " + (end - begin)
                + " milliseconds");

    }

    /**
     * {@inheritDoc}
     */
    public void contextDestroyed(ServletContextEvent event)
    {
        try
        {
            if (initLoader != null)
            {
                initLoader.destory();
            }
        }
        finally
        {
            super.contextDestroyed(event);
        }
    }

    private void processFailure(Throwable e)
    {

        log.error("System Init Loader  Start error ", e);
    }
}
